import {Injectable, EventEmitter, Inject} from '@angular/core';
import {Todo} from '../model/todo-model';

import {Observable} from 'rxjs/Rx';
import {AuthUserService} from '../../auth/auth-user.service';
import {LocalStorage} from '../../utils/local-storage';

@Injectable()
export class TodoService {

    change: EventEmitter<boolean>;

    constructor(private authUserService: AuthUserService,
                @Inject(LocalStorage) private localStorage) {
        this.change = new EventEmitter();
    }

    public save(todoContext: string): void {
        this.authUserService.getCurrentUser().subscribe(user => {
            const todo: Todo = new Todo();
            todo.context = todoContext;
            todo.completed = false;
            todo.userId = user.id;

            const todoList: Todo[] = this.getList(false);
            todoList.push(todo);
            this.localStorage.setItem('todo-list', JSON.stringify(todoList));
        });
    }

    public pushToCompleted(todo: Todo): void {
        const todoList: Todo[] = this.getList(false);
        const newTodoList: Todo[] = [];
        const completedTodoList: Todo[] = this.getList(true);
        todoList.forEach((value, index)  => {
            if (todo.context === value.context) {
                value.completed = true;
                completedTodoList.push(value);
            } else {
                newTodoList.push(value);
            }
        });

        this.localStorage.setItem('todo-list', JSON.stringify(newTodoList));
        this.localStorage.setItem('todo-completed-list', JSON.stringify(completedTodoList));
    }

    public pushToUnCompleted(todo: Todo): void {
        const todoList: Todo[] = this.getList(false);
        const newTodoList: Todo[] = [];
        const completedTodoList: Todo[] = this.getList(true);
        completedTodoList.forEach((value, index)  => {
            if (todo.context === value.context) {
                value.completed = false;
                todoList.push(value);
            } else {
                newTodoList.push(value);
            }
        });

        this.localStorage.setItem('todo-list', JSON.stringify(todoList));
        this.localStorage.setItem('todo-completed-list', JSON.stringify(newTodoList));
    }

    public getList(completed: boolean): Todo[] {
        let todoList: Array<Todo> = [];
        this.authUserService.getCurrentUser().subscribe(user => {
            const todoListValue = this.localStorage.getItem(completed ? 'todo-completed-list' : 'todo-list');
            if (!(todoListValue == null || todoListValue === '')) {
                todoList = JSON.parse(todoListValue);
            }
            todoList = todoList.filter(todo => todo.userId === user.id);
        });
        return todoList;
    }

}
